package beans;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.oreilly.servlet.MultipartRequest;





public class UserDAO {
	
	public boolean insertphoto(HttpServletRequest request) {
		System.out.println("进入insertphoto");
		boolean flag=false;
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}//防止有乱码
		
		//1定义保存图片的目录
		String saveDirectory = request.getSession().getServletContext().getRealPath("")+"\\upload";
		File savedir = new File(saveDirectory);//File可表示目录，也可表示文件
		if (!savedir.exists()) { savedir.mkdirs();}
		
		//2 定义MultipartRequest对象，接各类参数，保存上传的文件
		int maxPostSize = 5 * 1024 * 1024; // 什么意思？5M
		MultipartRequest multiRequest=null;	
		try {
			multiRequest = new MultipartRequest(request,saveDirectory, maxPostSize, "utf-8");
		} catch (IOException e) {			
			e.printStackTrace();
		}
		
		String userno = multiRequest.getParameter("userno");//先取一个用户号备用，因为要求保存的文件名是:用户号.png
		request.getSession().setAttribute("userno", userno);
		
		
		Enumeration<String> userFileEnumeration = multiRequest.getFileNames();//标记名列表
		String htmlname = userFileEnumeration.nextElement();//html的name属性，如userphoto
		File sendFile=multiRequest.getFile(htmlname);//是接收到的真正的文件
		String sendFileName = multiRequest.getFilesystemName(htmlname);//是接收到的真正的文件名，如test.png
		//测试接到的文件
		System.out.println("测试接到的文件:"+sendFileName);
		String suffix = sendFileName.substring(sendFileName.lastIndexOf(".") + 1);//取文件的扩展名，如png
		File oldFile=new File(saveDirectory+"\\"+userno+"."+suffix);
		if(oldFile.exists()){
			oldFile.delete();						
		}
		sendFile.renameTo(oldFile);
			
		//接其他参数
		String userpwd = multiRequest.getParameter("userpwd");
		String username = multiRequest.getParameter("username");
		String usersex = multiRequest.getParameter("usersex");
		String userage = multiRequest.getParameter("userage");
		String useraddress = multiRequest.getParameter("useraddress");
		String userprofession = multiRequest.getParameter("userprofession");
		String useremail = multiRequest.getParameter("useremail");
		String userphoto = userno+"."+suffix;
		String usersummary = multiRequest.getParameter("usersummary");
		
		String []userinterests = multiRequest.getParameterValues("userinterest");
		String userinterest="";
		for(int i=0;i<userinterests.length;i++){
			userinterest=userinterest+userinterests[i]+"-";
		}
		userinterest=userinterest.substring(0, userinterest.length()-1);
		
		//3写入数据库中
		User user=new User(0,userno, userpwd, username, usersex, userage, useraddress, userprofession, userinterest, useremail, userphoto, usersummary);
		flag=insert(user);
		return flag;
	}
	
	public int addnum() {	
		Connection con=null;
		PreparedStatement pst=null;		
		ResultSet rs=null;
		
		Connection con2=null;
		PreparedStatement pst2=null;
		ResultSet rs2=null;
		
		int n=0;
		try {
			con=DBConnection.getConnection();
			String sql="select * from fangwenrenshu";
			pst=con.prepareStatement(sql);

			rs=pst.executeQuery();
			if(rs.next()) {
				n=rs.getInt(1);
			}			
			n++;
			System.out.println("n is:"+n);
			
			con2=DBConnection.getConnection();
			String sql2="update  fangwenrenshu set num=?";
			pst2=con.prepareStatement(sql2);
			pst2.setInt(1, n);
			pst2.executeUpdate();
			
			
		} catch (Exception e) {
			// TODO: handle exception
		
		}finally {
			DBConnection.closeConnection(con, pst, rs);
			DBConnection.closeConnection(con2, pst2, rs2);
		}
		
		return n;
		
		
	}
	
	public int getnum() {	
		Connection con=null;
		PreparedStatement pst=null;		
		ResultSet rs=null;
		
		Connection con2=null;
		PreparedStatement pst2=null;
		ResultSet rs2=null;
		
		int n=0;

		try {
			con=DBConnection.getConnection();
			String sql="select * from fangwenrenshu";
			pst=con.prepareStatement(sql);

			rs=pst.executeQuery();
			if(rs.next()) {
				n=rs.getInt(1);
			}
		
			
		} catch (Exception e) {
			// TODO: handle exception
		
		}finally {
			DBConnection.closeConnection(con, pst, rs);
		}
		
		return n;		
		
	}
	
	
	public int addnumfile(HttpServletRequest request) {	
		String path1=request.getServletContext().getRealPath("");
		String path2=request.getSession().getServletContext().getRealPath("");//这个方法，无视tomcat版本
		//上面2方法效果完全一样，D:\eclipse-workspace-guangzi\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\javawebu5\
				
		path1=path1+"rs.txt";
		System.out.println("文件位置:"+path1);
		
		//下面是假如rs.txt文件没有，则拷贝一份，其实没有必要，事先在项目下建立一个文件rs.txt，里面放0即可。
		path2=path2+"/files/rs.txt";
		File file=new File(path1);//目标文件
		if(!file.exists()) {
			//copyfile(path2,path1);
			System.out.println("rs.txt不存在");
		}else {
			System.out.println("rs.txt存在");
		}
		
		int nums=0;
		BufferedReader br;
		try {//读出数据
			br=new BufferedReader(new InputStreamReader(new FileInputStream(path1)));
			nums=Integer.parseInt(br.readLine())+1;
			System.out.println("首次session佳话，得到的人数是:"+nums);
			
			br.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		BufferedWriter br2;
		try {//将加1放入文件
			br2=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path1)));
			br2.write(nums+"\n");
			br2.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
		}
		
		return nums;	
		
	}
	
	public int getnumfile(HttpServletRequest request) {	
		String path1=request.getServletContext().getRealPath("");
		String path2=request.getSession().getServletContext().getRealPath("");//这个方法，无视tomcat版本
		//上面2方法效果完全一样，D:\eclipse-workspace-guangzi\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\javawebu5\
				
		path1=path1+"rs.txt";
		System.out.println("文件位置:"+path1);
		
		//下面是假如rs.txt文件没有，则拷贝一份，其实没有必要，事先在项目下建立一个文件rs.txt，里面放0即可。
		path2=path2+"/files/rs.txt";
		File file=new File(path1);//目标文件
		if(!file.exists()) {
			//copyfile(path2,path1);
			System.out.println("rs.txt不存在");
		}else {
			System.out.println("rs.txt存在");
		}
		
		int nums = 0;
		BufferedReader br;
		try {//读出数据
			br=new BufferedReader(new InputStreamReader(new FileInputStream(path1)));
			nums=Integer.parseInt(br.readLine());
			System.out.println("非首次session佳话，如刷新，得到的人数是:"+nums);
			
			br.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return nums;	
		
	}
	
	public boolean delete(String userno) {
		System.out.println("delete"+userno);
		Connection con=null;
		PreparedStatement pst=null;
		ResultSet rs=null;
		boolean flag=false;
		try {
			con=DBConnection.getConnection();
			String sql="delete from user where user_no=?";
			pst=con.prepareStatement(sql);
			pst.setString(1, userno);
			int n=pst.executeUpdate();
			if(n>0) {
				flag=true;
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}		finally {
			DBConnection.closeConnection(con, pst, rs);			
		}
		return flag;
	}
	
	public boolean login(String userno,String pwd) {
		Connection con=null;
		PreparedStatement pst=null;
		ResultSet rs=null;
		
		boolean flag=false;
		
		try {
			con=DBConnection.getConnection();
			String sql="select * from user";
			pst=con.prepareStatement(sql);
			rs=pst.executeQuery();
			if(rs.next()) {
				System.out.println("ok");
				flag=true;
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			
		}finally {
			DBConnection.closeConnection(con, pst, rs);
		}
		return flag;		
	}
	
	public Map<String, Object> findone(String userno) {
		System.out.println("进入findone 参数userno is:"+userno);
		Connection con=null;
		PreparedStatement pst=null;
		ResultSet rs=null;
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		try {
			con=DBConnection.getConnection();
			String sql="select * from user where user_no=?";
			pst=con.prepareStatement(sql);
			pst.setString(1, userno);
			rs=pst.executeQuery();
			String[] keys= {"userno","userpwd","username","usersex","userage","useraddress","userprofession","userinterest","useremail","userphoto","usersummary"};
			
			if(rs.next()) {
				for(int i=0;i<keys.length;i++) {
					map.put(keys[i], rs.getString(i+2));
				}
			}			
		} catch (Exception e) {
			// TODO: handle exception
			
		}finally {
			DBConnection.closeConnection(con, pst, rs);
		}
		System.out.println("findone is:"+map.toString());
		return map;		
	}
	
	public User findone2(String userno) {
		System.out.println("进入findone 参数userno is:"+userno);
		Connection con=null;
		PreparedStatement pst=null;
		ResultSet rs=null;
		
		User user=new User();
		try {
			con=DBConnection.getConnection();
			String sql="select * from user where user_no=?";
			pst=con.prepareStatement(sql);
			pst.setString(1, userno);
			rs=pst.executeQuery();
			if(rs.next()) {			
				user.setUserid(rs.getInt(1));
				user.setUserno(rs.getString(2));
				user.setUserpwd(rs.getString(3));
				user.setUsername(rs.getString(4));
				user.setUsersex(rs.getString(5));
				user.setUserage(rs.getString(6));
				user.setUseraddress(rs.getString(7));
				user.setUserprofession(rs.getString(8));
				user.setUserinterest(rs.getString(9));
				user.setUseremail(rs.getString(10));
				user.setUserphoto(rs.getString(11));
				user.setUsersummary(rs.getString(12));
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			DBConnection.closeConnection(con, pst, rs);
		}
	
		return user;		
	}

	
	public boolean insert(String userno,String userpwd,String username,String usersex,String userage,String useraddress,String userprofession,String userinterest,String useremail,String userphoto,String usersummary) {
		Connection con=null;
		PreparedStatement pst=null;
		ResultSet rs=null;
		
		boolean flag=false;
		try {
			con=DBConnection.getConnection();
			String sql="insert into user values(null,?,?,?,?,?,?,?,?,?,?,?)";
			pst=con.prepareStatement(sql);
			pst.setString(1, userno);
			pst.setString(2, userpwd);
			pst.setString(3, username);
			pst.setString(4, usersex);
			pst.setString(5, userage);
			pst.setString(6, useraddress);
			pst.setString(7, userprofession);
			pst.setString(8, userinterest);
			pst.setString(9, useremail);
			pst.setString(10, userphoto);
			pst.setString(11, usersummary);
			int n=pst.executeUpdate();
			if(n>=1) {
				flag=true;
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			DBConnection.closeConnection(con, pst, rs);
		}
		return flag;
	}
	
	public boolean insert(User user) {
		Connection con=null;
		PreparedStatement pst=null;
		ResultSet rs=null;
		System.out.println(user);
		
		boolean flag=false;
		try {
			con=DBConnection.getConnection();
			String sql="insert into user values(null,?,?,?,?,?,?,?,?,?,?,?)";
			pst=con.prepareStatement(sql);
			pst.setString(1, user.getUserno());
			pst.setString(2, user.getUserpwd());
			pst.setString(3, user.getUsername());
			pst.setString(4, user.getUsersex());
			pst.setString(5, user.getUserage());
			pst.setString(6, user.getUseraddress());
			pst.setString(7, user.getUserprofession());
			pst.setString(8, user.getUserinterest());
			pst.setString(9, user.getUseremail());
			pst.setString(10, user.getUserphoto());
			pst.setString(11, user.getUsersummary());
			int n=pst.executeUpdate();
			if(n>=1) {
				flag=true;
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			DBConnection.closeConnection(con, pst, rs);
		}
		return flag;
	}
	
	
	public ArrayList<Map<String,Object>> findall(){
		Connection con=null;
		PreparedStatement pst=null;
		ResultSet rs=null;
		ArrayList<Map<String, Object>> al=new ArrayList<>();

		try {
			con=DBConnection.getConnection();
			String sql="select * from user";
			pst=con.prepareStatement(sql);
			
			rs=pst.executeQuery();
			String[] keys= {"userno","userpwd","username","usersex","userage","useraddress","userprofession","userinterest","useremail","userphoto","usersummary"};
			while(rs.next()) {
				Map<String, Object> map=new HashMap<>();
				for(int i=0;i<keys.length;i++) {
					map.put(keys[i], rs.getString(i+2));
				}
				al.add(map);
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			DBConnection.closeConnection(con, pst, rs);
		}
		return al;
	}
	

	
	public ArrayList<User> findall2(){
		Connection con=null;
		PreparedStatement pst=null;
		ResultSet rs=null;
		ArrayList<User> al=new ArrayList<>();

		try {
			con=DBConnection.getConnection();
			String sql="select * from user";
			pst=con.prepareStatement(sql);
			
			rs=pst.executeQuery();
			while(rs.next()) {
				User user=new User();
				user.setUserid(rs.getInt(1));
				user.setUserno(rs.getString(2));
				user.setUserpwd(rs.getString(3));
				user.setUsername(rs.getString(4));
				user.setUsersex(rs.getString(5));
				user.setUserage(rs.getString(6));
				user.setUseraddress(rs.getString(7));
				user.setUserprofession(rs.getString(8));
				user.setUserinterest(rs.getString(9));
				user.setUseremail(rs.getString(10));
				user.setUserphoto(rs.getString(11));
				user.setUsersummary(rs.getString(12));

				al.add(user);
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			DBConnection.closeConnection(con, pst, rs);
		}
		return al;
	}
	
	public ArrayList<Map<String,Object>> findwhere(String sql){
		Connection con=null;
		PreparedStatement pst=null;
		ResultSet rs=null;
		ArrayList<Map<String, Object>> al=new ArrayList<>();

		try {
			con=DBConnection.getConnection();
			
			pst=con.prepareStatement(sql);
			
			rs=pst.executeQuery();
			String[] keys= {"userno","userpwd","username","usersex","userage","useraddress","userprofession","userinterest","useremail","userphoto","usersummary"};
			while(rs.next()) {
				Map<String, Object> map=new HashMap<>();
				for(int i=0;i<keys.length;i++) {
					map.put(keys[i], rs.getString(i+2));
				}
				al.add(map);
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			DBConnection.closeConnection(con, pst, rs);
		}
		return al;
	}
	
	public boolean update(String userno,String userpwd,String username,String usersex,String userage,String useraddress,String userprofession,String userinterest,String useremail,String userphoto,String usersummary) {
		System.out.println("进入更新函数，得到的参数是：");
		System.out.println(userno+userpwd+username+usersex+userage+useraddress+userprofession+userphoto+useremail+usersummary);
		Connection con=null;
		PreparedStatement pst=null;
		ResultSet rs=null;
		
		boolean flag=false;
		try {
			con=DBConnection.getConnection();			
			String sql="update user set user_no=?,user_pwd=?,user_name=?,user_sex=?,user_age=?,user_address=?,user_profession=?,user_interest=?,user_email=?,user_photo=?,user_summary=? where user_no=?";
			pst=con.prepareStatement(sql);
			pst.setString(1, userno);
			pst.setString(2, userpwd);
			pst.setString(3, username);
			pst.setString(4, usersex);
			pst.setString(5, userage);
			pst.setString(6, useraddress);
			pst.setString(7, userprofession);
			pst.setString(8, userinterest);
			pst.setString(9, useremail);
			pst.setString(10, userphoto);
			pst.setString(11, usersummary);
			pst.setString(12, userno);
			int n=pst.executeUpdate();
			if(n>=1) {
				flag=true;
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			DBConnection.closeConnection(con, pst, rs);
		}
		return flag;
	}
	
	void del() {
		JSONObject js;
		//JSONObject.toJavaObject(json, clazz)
		String json="{\"name\":\"xxx\",\"pwd\":\"111\"}";
	}

}
